package cn.miao.learn.ssh.services.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.miao.learn.ssh.beans.TGroup;
import cn.miao.learn.ssh.beans.TPerson;
import cn.miao.learn.ssh.services.TestHibernateService;

@Service(value="TestHibernate")
public class TestHibernateServiceImpl implements TestHibernateService {

	@Resource(name="sessionFactory")
	private SessionFactory factory;
	
	
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public List<TPerson> getTpersonList() {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(TPerson.class);
		List<TPerson> list = castList(TPerson.class, criteria.list());
		session.close();
		return list;
	}
	
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public List<TGroup> getTGroupList() {
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(TGroup.class);
		List<TGroup> list = criteria.list();
		session.close();
		return list;
	}
	
	public <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
	    List<T> r = new ArrayList<T>(c.size());
	    for(Object o: c)
	      r.add(clazz.cast(o));
	    return r;
	}
}
